# coding:utf-8
from django.contrib.auth import login, authenticate
from django.shortcuts import render
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.hashers import make_password
from django.db.models import Q
from django.views.generic.base import View
from forms import LoginForm, RegisterForm
from utils.email_sender import send_register_email
# Create your views here.
from users.models import UserProfile


class myAuthBackend(ModelBackend):
    def authenticate(self, username=None, password=None, **kwargs):
        try:  # 让可以用username和email都可以登录,这个需要在Settings中配置,不要走默认方法,走我们自己定制的登录方式
            user = UserProfile.objects.get(Q(username=username) | Q(email=username))  # 如果是交集,就用,号隔开
            if user.check_password(password):
                return user
        except Exception as e:
            return None


class LoginView(View):
    def get(self, request):
        return render(request, 'login.html', {})

    def post(self, request):
        login_form = LoginForm(request.POST)
        if login_form.is_valid():  # 验证form表单
            user_name = request.POST.get('username')
            pass_word = request.POST.get('password')
            user = authenticate(username=user_name, password=pass_word)
            if user is not None:  # 验证成功,去登录
                login(request, user)  # 登录
                return render(request, 'login.html')
            else:  # 用户名密码错误
                return render(request, 'login.html', {'msg': '用户名不存在或者密码错误'})
        else:  # form表单格式错误
            return render(request, 'login.html', {'login_form': login_form})


class RegisterView(View):
    def get(self, request):
        register_form = RegisterForm()
        return render(request, 'register.html', {'register_form': register_form})

    def post(self, request):
        register_form = RegisterForm(request.POST)
        if register_form.is_valid():
            email = request.POST.get('email', '')
            pass_word = request.POST.get('password', '')
            pass_word = make_password(password=pass_word)
            user_profile = UserProfile()
            user_profile.username = email
            user_profile.email = email
            user_profile.password = pass_word
            user_profile.save()
            send_register_email(email)

        return render(request, 'register.html', {'register_form': register_form})

# def user_login(request):
#     if request.method == 'POST':  # 如果post请求就处理,否则还是返回登录页
#         user_name = request.POST.get('username')
#         pass_word = request.POST.get('password')
#         user = authenticate(username=user_name, password=pass_word)
#         if user is not None:  # 验证成功,去登录
#             login(request, user)  # 登录
#             return render(request, 'login.html', {})
#         else:  # 验证失败
#             return render(request, 'login.html', {'msg': '用户名不存在或者密码错误'})
#     elif request.method == 'GET':
#         return render(request, 'login.html', {})
